package com.nidu.demo.log.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.log.convertor.LoginLogConvertor;
import com.nidu.demo.log.gateway.LoginLogGateway;
import com.nidu.demo.log.mapper.LoginLogMapper;
import com.nidu.demo.log.mapper.dataobject.LoginLogDO;
import com.nidu.demo.log.model.LoginLog;
import com.nidu.demo.log.model.LoginLogCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 登录日志网关实现
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class LoginLogGatewayImpl implements LoginLogGateway {

    private final LoginLogMapper mapper;
    private final LoginLogConvertor convertor;

    @Override
    public LoginLog create(LoginLog loginLog) {
        LoginLogDO loginLogDO = convertor.toDataObject(loginLog);
        mapper.insert(loginLogDO);
        return convertor.toDomainObject(loginLogDO);
    }

    @Override
    public LoginLog update(LoginLog loginLog) {
        LoginLogDO loginLogDO = convertor.toDataObject(loginLog);
        mapper.updateById(loginLogDO);
        return convertor.toDomainObject(loginLogDO);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    public LoginLog getById(Long id) {
        LoginLogDO loginLogDO = mapper.selectById(id);
        if (loginLogDO == null) {
            return null;
        }
        return convertor.toDomainObject(loginLogDO);
    }

    @Override
    public List<LoginLog> getByIds(Set<Long> ids) {
        LambdaQueryWrapper<LoginLogDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(LoginLogDO::getId, ids);
        List<LoginLogDO> loginLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(loginLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(loginLogDOS);
    }

    @Override
    public List<LoginLog> listByCondition(LoginLogCriteria criteria) {
        LambdaQueryWrapper<LoginLogDO> wrapper = buildQueryWrapper(criteria);
        List<LoginLogDO> loginLogDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(loginLogDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(loginLogDOS);
    }

    @Override
    public PageResponse<LoginLog> pageByCondition(LoginLogCriteria criteria) {
        // 创建查询条件
        LambdaQueryWrapper<LoginLogDO> wrapper = buildQueryWrapper(criteria);

        // 创建分页对象
        Page<LoginLogDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }

        // 执行分页查询
        mapper.selectPage(page, wrapper);
        List<LoginLog> loginLogs = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(loginLogs, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public void deleteAll() {
        mapper.deleteAll();
    }

    @Override
    public LoginLog getLastLoginSuccessLog(Long userId) {
        return mapper.getLastLoginSuccessLog(userId);
    }

    private LambdaQueryWrapper<LoginLogDO> buildQueryWrapper(LoginLogCriteria criteria) {
        LambdaQueryWrapper<LoginLogDO> wrapper = new LambdaQueryWrapper<>();
        
        // 时间范围条件
        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(LoginLogDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(LoginLogDO::getCreateTime, createTime[0], createTime[1]);
            }
        }
        
        // 登录时间范围条件（使用createTime作为登录时间）
        LocalDateTime[] loginTime = criteria.getLoginTime();
        if (loginTime != null) {
            if (loginTime.length == 1 && loginTime[0] != null) {
                wrapper.ge(LoginLogDO::getCreateTime, loginTime[0]);
            } else if (loginTime.length > 1 && loginTime[0] != null && loginTime[1] != null) {
                wrapper.between(LoginLogDO::getCreateTime, loginTime[0], loginTime[1]);
            }
        }
        
        // 精确查询条件
        wrapper.eq(criteria.getUserId() != null, LoginLogDO::getUserId, criteria.getUserId());
        wrapper.eq(criteria.getLoginType() != null, LoginLogDO::getLoginType, criteria.getLoginType());
        wrapper.eq(criteria.getResult() != null, LoginLogDO::getResult, criteria.getResult());
        
        // 模糊查询条件
        wrapper.like(!StrUtil.isEmpty(criteria.getUserIp()), LoginLogDO::getUserIp, criteria.getUserIp());
        wrapper.like(!StrUtil.isEmpty(criteria.getUserAgent()), LoginLogDO::getUserAgent, criteria.getUserAgent());
        wrapper.like(!StrUtil.isEmpty(criteria.getUsername()), LoginLogDO::getUsername, criteria.getUsername());
        
        return wrapper;
    }

}
